package com.woniumall.service.impl;

import com.woniumall.dao.CartDao;
import com.woniumall.dao.CategoryDao;
import com.woniumall.dao.GoodsDao;
import com.woniumall.pojo.Cart;
import com.woniumall.pojo.Goods;
import com.woniumall.service.CartService;
import com.woniumall.util.sqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;
import java.util.List;

/**
 * @auther linke
 * @create 2021-10-31 17:47
 */
public class CartServiceImpl implements CartService {
    private SqlSession session;
    //获得持久层操作对象
    private CartDao cartDao;
    private GoodsDao goodsDao;
    @Override
    public void joinCart(int uid, int gid, int nums) {
        session = sqlSessionUtil.sqlSession();
        cartDao= session.getMapper(CartDao.class);
        goodsDao= session.getMapper(GoodsDao.class);
        //判断是不是第一次添加
        Cart cart = cartDao.findByUidAndGid(uid, gid);
        //根据商品id查询
        Goods goods = goodsDao.findById(gid);

        if(cart == null){//第一次
            Cart _cart = new Cart();
            _cart.setUserid(uid);
            _cart.setGoodsid(gid);
            _cart.setNums(nums);
            //价格转换计算
            BigDecimal price = goods.getSalesprice().multiply(new BigDecimal(nums));
            _cart.setPrice(price);
            //添加操作
            cartDao.add(_cart);
            session.commit();//提交事务
        }else{//不是第一次
            //修改数量
            int _nums = cart.getNums() + nums;
            cart.setNums(_nums);
            //修改价格
            BigDecimal _price = goods.getSalesprice().multiply(new BigDecimal(_nums));
            cart.setPrice(_price);
            //修改购物车对象
            cartDao.update(cart);
            session.commit();//提交事务
            session.close();//释放资源
        }
    }

    @Override
    public List<Cart> findAllByUid(int userId) {
        session = sqlSessionUtil.sqlSession();
        cartDao= session.getMapper(CartDao.class);

        List<Cart> list = cartDao.findAllByUid(userId);

        System.out.println(list);
        session.close();
        return list;
    }

    @Override
    public int countOrderByUserId(int userId) {
        session = sqlSessionUtil.sqlSession();
        cartDao= session.getMapper(CartDao.class);
        int orderNums = cartDao.findAllByUserid(userId);

        session.close();
        return orderNums;
    }

    @Override
    public void remove(int id) {
        session = sqlSessionUtil.sqlSession();
        cartDao= session.getMapper(CartDao.class);
        cartDao.removeByCartId(id);

        session.commit();
        session.close();//释放资源
    }
    //同步购物车页面数量
    @Override
    public void updateNums(int cartId, int nums) {
        session = sqlSessionUtil.sqlSession();
        cartDao= session.getMapper(CartDao.class);


        cartDao.updateNums(cartId,nums);


        session.commit();
        session.close();
    }

}
